
import CryptoJS from "crypto-js";
import {useTokenStore} from '@/store/modules/tokenStore'

let secret = 'abcdefghijklmn12'; //密钥
let iv = 'abcdefghijklmn12';

export function getAesString(data, key, iv) {
  let newKey = CryptoJS.enc.Utf8.parse(key);
  let newIv = CryptoJS.enc.Utf8.parse(iv);
  let encrypted = CryptoJS.AES.encrypt(data, newKey, {
    iv: newIv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString(); //返回的是base64格式的密文  
}

export function getDAesString(encrypted, key, iv) {
  let newKey = CryptoJS.enc.Utf8.parse(key);
  let newIv = CryptoJS.enc.Utf8.parse(iv);
  let decrypted = CryptoJS.AES.decrypt(encrypted, newKey, {
    iv: newIv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

function getAES(data) { //加密
  // let secret = 'abcdefghijklmn12'; //密钥
  // let iv = 'abcdefghijklmn12';
  let encrypted = getAesString(data, secret, iv); //密文
  return encrypted;
}

function getDAes(encrypted) { //解密
  let key = 'abcdefghijklmn12';
  let iv = 'abcdefghiiklmn12';
  let decryptedStr = getDAesString(encrypted, key, iv);
  return decryptedstr;
}

/**
 * @返回bodyDAes
 * @param {*} config 
 */
function responseDAes(config) {
  const oldSuccessFn = config.success;

  if(oldSuccessFn) {
    config.success = function(res) {
      const { header, data } = res;
      const dzEncrypt = header['DZ-ENCRYPT'];
      if(dzEncrypt === "1") {
        
        const myRecommendCode = useTokenStore().userInfo().recommendCode;
        if(myRecommendCode) {
          const key = getEncryptKey(myRecommendCode);
          const iv = getEncryptKey(myRecommendCode, true);
  
          console.log("解密前的数据：", res.data);
  
          const dData = getDAesString(data, key, iv);
  
          console.log("解密后的数据：", dData);
          try {
            res.data = JSON.parse(dData)
          } catch(e) {
            res.data = dData;
          }
        }
      }
  
      oldSuccessFn(res);
    }
  }
}

/**
 * @用户信息DAes
 * @param {*} userInfo 
 */
function userInfoDAes(userInfo, recommendCode) {

}

export function getEncryptKey(recommendCode = "", isIv = false, len = 16) {
  let str = "";
  if(isIv) {
    let array = recommendCode.split("").reverse();
    recommendCode = array.join("")
  }

  while(str.length < len) {
    str += recommendCode;
  }

  const result = str.slice(0, len);
  return result;
}

// export default  {
//   getAesString,
//   getDAesString,
//   getAES,
//   getDAes,
//   responseDAes
// }